package com.sky.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class AliOss {

    public static final String END_POINT = "http://oss-cn-beijing.aliyuncs.com";

    public static final String ACCESS_KEY_ID = "LTAI4GKK5DZLmYg3kvK7pJZn";

    public static final String ACCESS_KEY_SECRET = "pFDbrgXFe6EGaXnuTDZO27G2cDL1M4";

    public static final String BUCKET_NAME = "hctsky";

    public static void upload(){
        File file = new File("/Volumes/Andy/u=1533263413,4245234134&fm=26&gp=0.jpg");
        try {
            InputStream fileContent=null;
            fileContent=new FileInputStream(file);
            // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，
            // 创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(fileContent.available());
            objectMetadata.setCacheControl(BUCKET_NAME);
            objectMetadata.setHeader("Pragma", BUCKET_NAME);
            objectMetadata.setContentEncoding("utf-8");
            objectMetadata.setContentType("application/x-msdownload");
            objectMetadata.setContentDisposition("attachment;filename=" + file.getName());

            // 创建OSSClient实例
            OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            // 上传文件
            PutObjectResult putObject = ossClient.putObject(BUCKET_NAME, file.getName(), fileContent, objectMetadata);

            // 关闭client
            ossClient.shutdown();

            System.out.println("http://" + BUCKET_NAME + ".oss-cn-beijing.aliyuncs.com/"+file.getName());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        upload();
    }
}
